package com.zzzy.doc.service.mydoc;

import com.zzzy.common.util.AssertUtil;
import com.zzzy.doc.common.enums.DocNotifyMessageModuleEnum;
import com.zzzy.doc.common.enums.DocReceiveSourceEnum;
import com.zzzy.doc.common.enums.DocReceiveStatusEnum;
import com.zzzy.doc.common.enums.DocStatusEnum;
import com.zzzy.doc.dao.entity.DocReceiveRecord;
import com.zzzy.doc.dao.entity.Document;
import com.zzzy.doc.service.exchange.DocReceiveRecordService;
import com.zzzy.doc.service.exchange.DocSendRecordService;
import com.zzzy.sys.api.UserApi;
import com.zzzy.sys.dto.UserInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MyDocDistributeService extends MyDocService {

    @Resource
    private DocSendRecordService docSendRecordService;
    @Resource
    private DocReceiveRecordService docReceiveRecordService;
    @Resource
    private UserApi userService;

    @Transactional
    public void distributeAndComplete(Long id) {
        Document document = getDocByIdForUpdate(id);
        AssertUtil.isEquals(DocStatusEnum.DISTRIBUTE.getValue(), document.getStatus(), "公文状态错误，无法进入办结阶段");
        docAdviceService.addAdvice(id, "分发完毕进入办结阶段");

        document.setStatus(DocStatusEnum.COMPLETE.getValue());
        document.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(document);

        sendDoc(id);
    }

    private void sendDoc(Long id) {
        Document document = getDocByIdForUpdate(id);
        Long sendRecordId = docSendRecordService.addSendRecordByDocId(id);

        List<DocReceiveRecord> receiveRecordList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        if (StringUtils.isNotBlank(document.getMainSendUnitIds())){
            Long[] mainDeptIds = Arrays.stream(document.getMainSendUnitIds().split(",")).map(Long::parseLong).collect(Collectors.toList()).toArray((new Long[0]));
            List<UserInfoDto> userInfoDtoList = userService.getUserInfoListByDeptId(mainDeptIds);
            //过滤出 有收文权限的用户
            userInfoDtoList = filterReceiveUserList(userInfoDtoList);
            List<DocReceiveRecord> mainSendRecord = userInfoDtoList.stream().map(userInfoDto -> {
                DocReceiveRecord receiveRecord = new DocReceiveRecord();
                receiveRecord.setDocId(id);
                receiveRecord.setSendRecordId(sendRecordId);
                receiveRecord.setReceiveUserId(userInfoDto.getId());
                receiveRecord.setReceiveUserName(userInfoDto.getNickName());
                receiveRecord.setReceiveTime(now);
                receiveRecord.setReceiveDeptId(userInfoDto.getDeptId());
                receiveRecord.setReceiveSource(DocReceiveSourceEnum.MAIN_SEND.getValue());
                receiveRecord.setStatus(DocReceiveStatusEnum.TO_BE_RECEIVED.getValue());
                return receiveRecord;
            }).collect(Collectors.toList());
            receiveRecordList.addAll(mainSendRecord);
        }
        if (StringUtils.isNotBlank(document.getCopySendUnitIds())){
            Long[] copyDeptIds = Arrays.stream(document.getCopySendUnitIds().split(",")).map(Long::parseLong).collect(Collectors.toList()).toArray((new Long[0]));
            List<UserInfoDto> userInfoDtoList = userService.getUserInfoListByDeptId(copyDeptIds);
            //过滤出 有收文权限的用户
            userInfoDtoList = filterReceiveUserList(userInfoDtoList);
            List<DocReceiveRecord> copySendRecord = userInfoDtoList.stream().map(userInfoDto -> {
                DocReceiveRecord receiveRecord = new DocReceiveRecord();
                receiveRecord.setDocId(id);
                receiveRecord.setSendRecordId(sendRecordId);
                receiveRecord.setReceiveUserId(userInfoDto.getId());
                receiveRecord.setReceiveUserName(userInfoDto.getNickName());
                receiveRecord.setReceiveTime(now);
                receiveRecord.setReceiveDeptId(userInfoDto.getDeptId());
                receiveRecord.setReceiveSource(DocReceiveSourceEnum.COPY_SEND.getValue());
                receiveRecord.setStatus(DocReceiveStatusEnum.TO_BE_RECEIVED.getValue());
                return receiveRecord;
            }).collect(Collectors.toList());
            receiveRecordList.addAll(copySendRecord);
        }
        if (!CollectionUtils.isEmpty(receiveRecordList)){
            docReceiveRecordService.saveBatch(receiveRecordList);

            String message = "接收到新公文：" + document.getSubject();
            for (DocReceiveRecord receiveRecord : receiveRecordList) {
                docNotifyMessageService.addNotifyMessage(receiveRecord.getId(), receiveRecord.getReceiveUserId(), DocNotifyMessageModuleEnum.EXCHANGE_RECEIVE, message);
            }
        }
    }

    /**
     * 过滤出 有收文权限的用户
     */
    private List<UserInfoDto> filterReceiveUserList(List<UserInfoDto> userInfoDtoList) {
        return userInfoDtoList.stream().filter(userInfoDto -> userService.hasPermission(userInfoDto.getId(), "doc:exchange:receive:page")).collect(Collectors.toList());
    }
}
